<template>
  <el-dialog class="vbuser-dialog" width="800px" append-to-body :visible="visible" :close-on-click-modal="false" title="选择" @close="handleClose">
    <div class="vb-user-dialog">
      <div class="user-dialog-tree">
        <div class="dialog-tree-filter">
          <el-input v-model="filterText" placeholder="输入关键字查找" />
        </div>
        <div class="dialog-tree-content">
          <el-tree
            ref="tree"
            :data="data"
            node-key="id"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" :class="['custom-tree-node', 'active'] ">
              <span>{{ node.label }}</span>
              <span>
                <i v-if="selectedIds.indexOf(data.id)>=0" class="el-icon-check" />
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <div class="user-dialog-selected">
        <div class="dialog-selected-top">
          <span>已选：{{ selected.length }}个{{ type==='user'?'员工':'部门' }}</span>
          <el-button type="text" :disabled="selected.length<=0">清空</el-button>
        </div>
        <el-scrollbar>
          <div class="select-list">
            <div v-for="(s,index) in selected" :key="index" class="select-item">
              <div class="item-name">{{ s.name }}</div>
              <div class="item-clear">
                <i class="el-icon-circle-close" @click="handleDel(index)" />
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getDeptAndUser } from '@/api/user'
import { getTenantId } from '@/utils/auth'
export default {
  name: 'VbUsers',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'user' // dept 为只显示部门
    },
    value: {
      type: [Array, Object],
      default: () => {
        return []
      }
    },
    single: {
      type: Boolean,
      default: true
    },
    displayUserName: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      filterText: '',
      data: [],
      selected: []
    }
  },
  computed: {
    selectedIds() {
      return this.selected.map((m) => m.id)
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    const tenantId = getTenantId()
    getDeptAndUser({ tenantId, includeUser: this.type === 'user' }).then(res => {
      console.log(res)
      this.data = this.formatUserData(res)
    })
    if (Array.isArray(this.value)) {
      this.selected = this.value.map(m => {
        m.id = this.type === 'user' ? `user-${m.id}` : m.id
        return m
      })
    }
    if (this.value && this.value.id) {
      this.selected = [this.value]
    }
    console.log('this.selected :', this.selected)
  },
  methods: {
    handleClose() {
      console.log('ssdsd')
      this.$emit('close')
    },
    handleDel(i) {
      const select = JSON.parse(JSON.stringify(this.selected))
      select.splice(i, 1)
      this.selected = select
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleConfirm() {
      if (this.selected.length <= 0) {
        this.$message.warn('请选择')
        return
      }
      if (this.single) {
        this.$emit('input', JSON.parse(JSON.stringify(this.selected[0])))
        this.$emit('close', JSON.parse(JSON.stringify(this.selected[0])))
        return
      }
      this.$emit('input', JSON.parse(JSON.stringify(this.selected)))
      this.$emit('close', JSON.parse(JSON.stringify(this.selected)))
    },
    handleNodeClick(data, node) {
      console.log('data-node:', data, node)
      if (this.type === 'user' && data.isUser) {
        if (this.single) {
          this.selected = [{
            name: data.name,
            id: data.value,
            userName: data.userName
          }]
        } else {
          this.selected.push({
            name: data.name,
            id: data.value,
            userName: data.userName
          })
        }
      } else if (this.type === 'dept') {
        if (this.single) {
          this.selected = [{
            name: data.label,
            id: data.value
          }]
        } else {
          this.selected.push({
            name: data.label,
            id: data.value
          })
        }
      }
    },
    formatUserData(list) {
      if (list && list.length > 0) {
        return list.map(l => {
          let userNodes = []
          let childrenNodes = []
          if (l.userList && l.userList.length > 0) {
            userNodes = l.userList.map(m => {
              return {
                name: `${m.nickname}`,
                value: m.userId,
                isleaf: true,
                isUser: true,
                userName: m.username,
                id: `user-${m.userId}`,
                children: null
              }
            })
          }
          if (l.children && l.children.length > 0) {
            childrenNodes = l.children.map(m => {
              return {
                name: m.name,
                id: m.id,
                isleaf: false,
                children: m.children,
                userList: m.userList
              }
            })
          }

          return {
            label: l.userName ? (this.displayUserName ? `${l.name}(${l.userName})` : l.name) : l.name,
            value: l.isleaf ? l.value : l.id,
            isleaf: l.isleaf,
            isUser: l.isUser,
            name: l.name,
            userName: l.userName || '',
            id: `${l.id}`,
            children: this.formatUserData([...userNodes, ...childrenNodes])
          }
        })
      }
      return []
    }
  }
}
</script>
<style lang="scss">
.vbuser-dialog{
  .el-dialog__body{
    padding-top: 16px;
    padding-bottom: 0;
  }
}
.vb-user-dialog{
  display: flex;
   border: 1px solid #e5e5e5;
   .el-scrollbar__wrap{
    overflow-x: hidden;
   }
  .user-dialog-tree{
    height: 400px;
    flex: 1;
    display: flex;
    flex-direction: column;
    padding-right: 10px;
    border-right: 1px solid #e5e5e5;
     padding: 10px;
    .dialog-tree-filter{

    }
    .dialog-tree-content{

      flex: 1;
      overflow-y: auto;
      .custom-tree-node{
        flex: 1;
        display: flex;
        justify-content: space-between;
        .el-icon-check{
          color: $--color-primary;
          margin-right: 10px;
        }
      }

    }

  }
  .user-dialog-selected{
    height: 400px;
    flex: 1;
    padding: 10px;
    flex-direction: column;
    display: flex;
    .dialog-selected-top{
      display: flex;
      justify-content: space-between;
    }
    .select-list{
      flex: 1;
      height: 400px;
      overflow-y: auto;
      .select-item{
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 3px 10px ;
        &:hover{
          color: $--color-primary;
          background-color: #ecf5ff;
          cursor: pointer;

        }
        .item-name{
          flex: 1;

        }
        .item-clear{
          width: 30px;
          text-align: center;
          &:hover{
            color: $--color-primary;
            cursor: pointer;
          }
        }

      }
    }
  }

}
</style>
